import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox
import re
import os
import sys
import math as py_math
import time as py_time

class BraceLangIDE:
    def __init__(self, root):
        self.root = root
        self.root.title("BraceLang IDE")
        self.root.geometry("1000x700")
        
        # 初始化解释器
        self.interpreter = BraceLangInterpreter()
        
        # 设置主题颜色
        self.bg_color = "#f0f0f0"
        self.text_bg = "#ffffff"
        self.text_fg = "#000000"
        self.highlight_color = "#e0e0ff"
        
        # 创建界面
        self.create_menu()
        self.create_editor()
        self.create_output()
        self.create_status_bar()
        
        # 当前文件
        self.current_file = None
        
        # 设置语法高亮
        self.setup_syntax_highlighting()
        
        # 绑定事件
        self.editor.bind('<KeyRelease>', self.on_key_release)
        
    def create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self.root)
        
        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="新建", command=self.new_file, accelerator="Ctrl+N")
        file_menu.add_command(label="打开", command=self.open_file, accelerator="Ctrl+O")
        file_menu.add_command(label="保存", command=self.save_file, accelerator="Ctrl+S")
        file_menu.add_command(label="另存为", command=self.save_as_file, accelerator="Ctrl+Shift+S")
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.exit_ide)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        # 编辑菜单
        edit_menu = tk.Menu(menubar, tearoff=0)
        edit_menu.add_command(label="撤销", command=self.undo, accelerator="Ctrl+Z")
        edit_menu.add_command(label="重做", command=self.redo, accelerator="Ctrl+Y")
        edit_menu.add_separator()
        edit_menu.add_command(label="剪切", command=self.cut, accelerator="Ctrl+X")
        edit_menu.add_command(label="复制", command=self.copy, accelerator="Ctrl+C")
        edit_menu.add_command(label="粘贴", command=self.paste, accelerator="Ctrl+V")
        menubar.add_cascade(label="编辑", menu=edit_menu)
        
        # 运行菜单
        run_menu = tk.Menu(menubar, tearoff=0)
        run_menu.add_command(label="运行", command=self.run_code, accelerator="F5")
        run_menu.add_command(label="停止", command=self.stop_execution, accelerator="Ctrl+F2")
        menubar.add_cascade(label="运行", menu=run_menu)
        
        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="关于", command=self.show_about)
        menubar.add_cascade(label="帮助", menu=help_menu)
        
        self.root.config(menu=menubar)
        
        # 绑定快捷键
        self.root.bind('<Control-n>', lambda e: self.new_file())
        self.root.bind('<Control-o>', lambda e: self.open_file())
        self.root.bind('<Control-s>', lambda e: self.save_file())
        self.root.bind('<Control-Shift-S>', lambda e: self.save_as_file())
        self.root.bind('<F5>', lambda e: self.run_code())
        self.root.bind('<Control-F2>', lambda e: self.stop_execution())
        
    def create_editor(self):
        """创建代码编辑器"""
        # 创建框架
        editor_frame = ttk.Frame(self.root)
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 添加行号
        self.line_numbers = tk.Text(editor_frame, width=4, padx=5, pady=5, 
                                   takefocus=0, border=0, background='lightgrey',
                                   state='disabled')
        self.line_numbers.pack(side=tk.LEFT, fill=tk.Y)
        
        # 创建代码编辑器
        self.editor = scrolledtext.ScrolledText(editor_frame, wrap=tk.WORD, 
                                               undo=True, bg=self.text_bg, fg=self.text_fg,
                                               font=("Consolas", 12))
        self.editor.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 绑定事件
        self.editor.bind('<Button-1>', self.update_line_numbers)
        self.editor.bind('<MouseWheel>', self.update_line_numbers)
        
        # 初始化行号
        self.update_line_numbers()
        
    def create_output(self):
        """创建输出区域"""
        # 创建框架
        output_frame = ttk.LabelFrame(self.root, text="输出")
        output_frame.pack(fill=tk.BOTH, expand=False, padx=5, pady=5, ipady=5)
        
        # 创建输出文本框
        self.output = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, 
                                               height=10, bg=self.text_bg, fg=self.text_fg,
                                               font=("Consolas", 10))
        self.output.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.output.config(state=tk.DISABLED)
        
    def create_status_bar(self):
        """创建状态栏"""
        self.status_bar = ttk.Label(self.root, text="就绪", relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
    def setup_syntax_highlighting(self):
        """设置语法高亮"""
        # 关键字列表
        self.keywords = [
            'var', 'func', 'if', 'else', 'for', 'while', 'return', 'import'
        ]
        
        # 内置函数列表
        self.builtin_functions = [
            'print', 'sqrt', 'pow', 'sin', 'cos', 'tan', 'length', 'upper', 
            'lower', 'substring', 'time', 'sleep', 'exit', 'int', 'float', 
            'str', 'bool'
        ]
        
        # 库列表
        self.libraries = [
            'math', 'string', 'sys', 'convert'
        ]
        
        # 配置标签样式
        self.editor.tag_configure('keyword', foreground='blue', font=("Consolas", 12, 'bold'))
        self.editor.tag_configure('function', foreground='purple')
        self.editor.tag_configure('library', foreground='darkgreen')
        self.editor.tag_configure('string', foreground='brown')
        self.editor.tag_configure('comment', foreground='green')
        self.editor.tag_configure('number', foreground='red')
        
    def on_key_release(self, event=None):
        """按键释放事件处理"""
        self.update_line_numbers()
        # 延迟执行语法高亮，避免性能问题
        self.root.after(100, self.highlight_syntax)
        
    def update_line_numbers(self, event=None):
        """更新行号"""
        # 获取当前行数
        lines = self.editor.get('1.0', tk.END).count('\n')
        
        # 更新行号文本框
        self.line_numbers.config(state=tk.NORMAL)
        self.line_numbers.delete('1.0', tk.END)
        
        for i in range(1, lines + 1):
            self.line_numbers.insert(tk.END, f'{i}\n')
            
        self.line_numbers.config(state=tk.DISABLED)
        
    def highlight_syntax(self):
        """语法高亮"""
        # 移除所有现有的标签
        for tag in self.editor.tag_names():
            if tag != 'sel':  # 保留选择标签
                self.editor.tag_remove(tag, '1.0', tk.END)
        
        # 获取文本内容
        content = self.editor.get('1.0', tk.END)
        
        # 使用正则表达式查找所有匹配项
        self.highlight_with_regex(content, r'\b(var|func|if|else|for|while|return|import)\b', 'keyword')
        self.highlight_with_regex(content, r'\b(print|sqrt|pow|sin|cos|tan|length|upper|lower|substring|time|sleep|exit|int|float|str|bool)\b', 'function')
        self.highlight_with_regex(content, r'\b(math|string|sys|convert)\b', 'library')
        self.highlight_with_regex(content, r'"[^"]*"', 'string')
        self.highlight_with_regex(content, r'//.*', 'comment')
        self.highlight_with_regex(content, r'/\*.*?\*/', 'comment')
        self.highlight_with_regex(content, r'\b\d+\b', 'number')
        self.highlight_with_regex(content, r'\b\d+\.\d+\b', 'number')
    
    def highlight_with_regex(self, content, pattern, tag):
        """使用正则表达式高亮文本"""
        matches = re.finditer(pattern, content, re.MULTILINE | re.DOTALL)
        for match in matches:
            start = match.start()
            end = match.end()
            
            # 将字节偏移量转换为行和列
            start_line = content.count('\n', 0, start) + 1
            start_col = start - content.rfind('\n', 0, start)
            end_line = content.count('\n', 0, end) + 1
            end_col = end - content.rfind('\n', 0, end)
            
            # 应用标签
            self.editor.tag_add(tag, f"{start_line}.{start_col}", f"{end_line}.{end_col}")
        
    def new_file(self):
        """新建文件"""
        self.editor.delete('1.0', tk.END)
        self.current_file = None
        self.update_status("新建文件")
        
    def open_file(self):
        """打开文件"""
        file_path = filedialog.askopenfilename(
            defaultextension=".bl",
            filetypes=[("BraceLang Files", "*.bl"), ("All Files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                self.editor.delete('1.0', tk.END)
                self.editor.insert('1.0', content)
                self.current_file = file_path
                self.update_status(f"已打开: {file_path}")
                self.highlight_syntax()
                
            except Exception as e:
                messagebox.showerror("错误", f"无法打开文件: {e}")
    
    def save_file(self):
        """保存文件"""
        if self.current_file:
            try:
                content = self.editor.get('1.0', tk.END)
                with open(self.current_file, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                self.update_status(f"已保存: {self.current_file}")
            except Exception as e:
                messagebox.showerror("错误", f"无法保存文件: {e}")
        else:
            self.save_as_file()
    
    def save_as_file(self):
        """另存为文件"""
        file_path = filedialog.asksaveasfilename(
            defaultextension=".bl",
            filetypes=[("BraceLang Files", "*.bl"), ("All Files", "*.*")]
        )
        
        if file_path:
            try:
                content = self.editor.get('1.0', tk.END)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                self.current_file = file_path
                self.update_status(f"已保存: {file_path}")
            except Exception as e:
                messagebox.showerror("错误", f"无法保存文件: {e}")
    
    def exit_ide(self):
        """退出IDE"""
        if messagebox.askokcancel("退出", "确定要退出吗？"):
            self.root.destroy()
    
    def undo(self):
        """撤销"""
        try:
            self.editor.edit_undo()
        except:
            pass
    
    def redo(self):
        """重做"""
        try:
            self.editor.edit_redo()
        except:
            pass
    
    def cut(self):
        """剪切"""
        self.editor.event_generate("<<Cut>>")
    
    def copy(self):
        """复制"""
        self.editor.event_generate("<<Copy>>")
    
    def paste(self):
        """粘贴"""
        self.editor.event_generate("<<Paste>>")
    
    def run_code(self):
        """运行代码"""
        # 清空输出
        self.output.config(state=tk.NORMAL)
        self.output.delete('1.0', tk.END)
        
        # 获取代码
        code = self.editor.get('1.0', tk.END)
        
        # 重定向输出
        import io
        from contextlib import redirect_stdout, redirect_stderr
        
        stdout_capture = io.StringIO()
        stderr_capture = io.StringIO()
        
        try:
            # 执行代码并捕获输出
            with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
                self.interpreter.run(code)
            
            # 显示输出
            output_text = stdout_capture.getvalue()
            if output_text:
                self.output.insert(tk.END, output_text)
            
            # 显示错误
            error_text = stderr_capture.getvalue()
            if error_text:
                self.output.insert(tk.END, f"\n错误:\n{error_text}")
                
            self.update_status("代码执行完成")
            
        except Exception as e:
            self.output.insert(tk.END, f"执行错误: {e}")
            self.update_status(f"执行错误: {e}")
        
        self.output.config(state=tk.DISABLED)
    
    def stop_execution(self):
        """停止执行"""
        # 这里可以添加停止执行的逻辑
        self.update_status("执行已停止")
    
    def show_about(self):
        """显示关于信息"""
        about_text = """
BraceLang IDE

一个简单的 BraceLang 语言集成开发环境。

功能:
- 代码编辑与语法高亮
- 文件操作（新建、打开、保存）
- 代码执行与输出显示
- 基本编辑功能（撤销、重做、剪切、复制、粘贴）

BraceLang 是一种简单易学的解释型语言，使用大括号作为代码块分隔符。
        """
        messagebox.showinfo("关于 BraceLang IDE", about_text)
    
    def update_status(self, message):
        """更新状态栏"""
        self.status_bar.config(text=message)

# 下面是之前实现的 BraceLangInterpreter 类
class BraceLangInterpreter:
    def __init__(self):
        self.variables = {}
        self.functions = {}
        self.libraries = {}  # 存储已加载的库
        self.current_line = 0
        
        # 注册内置库
        self.register_builtin_libraries()
    
    def register_builtin_libraries(self):
        """注册内置库函数"""
        # 数学库
        self.libraries['math'] = {
            'sqrt': lambda args: py_math.sqrt(self.cast_number(args[0])),
            'pow': lambda args: self.cast_number(args[0]) ** self.cast_number(args[1]),
            'sin': lambda args: py_math.sin(self.cast_number(args[0])),
            'cos': lambda args: py_math.cos(self.cast_number(args[0])),
            'tan': lambda args: py_math.tan(self.cast_number(args[0])),
            'pi': lambda args: py_math.pi,
            'e': lambda args: py_math.e,
            'max': lambda args: max([self.cast_number(arg) for arg in args]),
            'min': lambda args: min([self.cast_number(arg) for arg in args]),
            'abs': lambda args: abs(self.cast_number(args[0])),
            'round': lambda args: round(self.cast_number(args[0]), int(args[1]) if len(args) > 1 else 0)
        }
        
        # 字符串库
        self.libraries['string'] = {
            'length': lambda args: len(str(args[0])),
            'upper': lambda args: str(args[0]).upper(),
            'lower': lambda args: str(args[0]).lower(),
            'substring': lambda args: str(args[0])[int(args[1]):int(args[2])],
            'contains': lambda args: str(args[1]) in str(args[0]),
            'replace': lambda args: str(args[0]).replace(str(args[1]), str(args[2])),
            'split': lambda args: str(args[0]).split(str(args[1]) if len(args) > 1 else " "),
            'trim': lambda args: str(args[0]).strip()
        }
        
        # 系统库
        self.libraries['sys'] = {
            'time': lambda args: py_time.time(),
            'sleep': lambda args: py_time.sleep(self.cast_number(args[0])),
            'exit': lambda args: exit(int(args[0]) if args else 0)
        }
        
        # 类型转换库
        self.libraries['convert'] = {
            'int': lambda args: int(self.cast_number(args[0])),
            'float': lambda args: float(self.cast_number(args[0])),
            'str': lambda args: str(args[0]),
            'bool': lambda args: bool(args[0])
        }
    
    def preprocess_code(self, code):
        """预处理代码，移除注释"""
        # 移除单行注释 (//)
        code = re.sub(r'//.*', '', code)
        
        # 移除多行注释 (/* ... */)
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        
        return code
    
    def cast_number(self, value):
        """将值转换为数字"""
        if isinstance(value, (int, float)):
            return value
        try:
            return float(value) if '.' in str(value) else int(value)
        except ValueError:
            return 0
    
    def tokenize(self, code):
        """词法分析器"""
        # 预处理代码，移除注释
        code = self.preprocess_code(code)
        
        tokens = []
        token_specification = [
            ('NUMBER',   r'\d+(\.\d*)?'),  
            ('STRING',   r'"[^"]*"'),       
            ('ID',       r'[A-Za-z_][A-Za-z0-9_]*'),
            ('OP',       r'[+\-*/=<>!&|]+'),
            ('SEMI',     r';'),
            ('COMMA',    r','),
            ('LPAREN',   r'\('),
            ('RPAREN',   r'\)'),
            ('LBRACE',   r'\{'),
            ('RBRACE',   r'\}'),
            ('SKIP',     r'[ \t\n]+'),
            ('MISMATCH', r'.'),
        ]
        
        tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
        line_num = 1
        
        for mo in re.finditer(tok_regex, code):
            kind = mo.lastgroup
            value = mo.group()
            
            if kind == 'NUMBER':
                value = float(value) if '.' in value else int(value)
            elif kind == 'STRING':
                value = value[1:-1]  # 去除引号
            elif kind == 'SKIP':
                if '\n' in value:
                    line_num += value.count('\n')
                continue
            elif kind == 'MISMATCH':
                # 忽略冒号，因为它是REPL命令的一部分
                if value == ':':
                    continue
                raise RuntimeError(f'Line {line_num}: Unexpected character: {value}')
            
            tokens.append((kind, value, line_num))
            if kind == 'STRING' and '\n' in value:
                line_num += value.count('\n')
        
        return tokens
    
    def parse(self, tokens):
        """语法分析器"""
        ast = []
        i = 0
        self.current_line = 0
        
        while i < len(tokens):
            token_type, token_value, line_num = tokens[i]
            self.current_line = line_num
            
            # 处理 import 语句
            if token_type == 'ID' and token_value == 'import':
                i += 1
                if i >= len(tokens) or tokens[i][0] != 'STRING':
                    raise SyntaxError("Expected library name after 'import'")
                
                lib_name = tokens[i][1]
                i += 1
                
                if i < len(tokens) and tokens[i][1] == ';':
                    i += 1
                
                ast.append(('import', lib_name, line_num))
                continue
            
            # 处理变量声明
            if token_type == 'ID' and token_value == 'var':
                i += 1
                if i >= len(tokens) or tokens[i][0] != 'ID':
                    raise SyntaxError("Expected variable name after 'var'")
                
                var_name = tokens[i][1]
                i += 1
                
                if i >= len(tokens) or tokens[i][1] != '=':
                    raise SyntaxError("Expected '=' after variable name")
                i += 1
                
                # 解析表达式直到分号
                expr_tokens = []
                while i < len(tokens) and tokens[i][1] != ';':
                    expr_tokens.append(tokens[i])
                    i += 1
                
                if i < len(tokens) and tokens[i][1] == ';':
                    i += 1
                
                ast.append(('var_decl', var_name, expr_tokens, line_num))
                continue
            
            # 处理函数调用
            if token_type == 'ID' and token_value in self.functions:
                func_name = token_value
                i += 1
                
                if i >= len(tokens) or tokens[i][1] != '(':
                    raise SyntaxError(f"Expected '(' after '{func_name}'")
                i += 1
                
                # 解析参数
                args = self.parse_arguments(tokens, i)
                i = self.find_token_end(tokens, i)
                
                ast.append(('func_call', func_name, args, line_num))
                continue
            
            # 处理 print 语句
            if token_type == 'ID' and token_value == 'print':
                i += 1
                if i >= len(tokens) or tokens[i][1] != '(':
                    raise SyntaxError("Expected '(' after 'print'")
                i += 1
                
                # 解析参数
                args = self.parse_arguments(tokens, i)
                i = self.find_token_end(tokens, i)
                
                ast.append(('func_call', 'print', args, line_num))
                continue
            
            i += 1
        
        return ast
    
    def parse_arguments(self, tokens, start_index):
        """解析函数参数"""
        args = []
        current_arg = []
        paren_count = 1
        i = start_index
        
        while i < len(tokens) and paren_count > 0:
            token_type, token_value, line_num = tokens[i]
            
            if token_value == '(':
                paren_count += 1
            elif token_value == ')':
                paren_count -= 1
            
            if paren_count == 1 and token_value == ',':
                args.append(current_arg)
                current_arg = []
            elif paren_count > 0:
                current_arg.append((token_type, token_value, line_num))
            
            i += 1
        
        if current_arg:
            args.append(current_arg)
        
        return args
    
    def find_token_end(self, tokens, start_index):
        """找到token的结束位置"""
        i = start_index
        paren_count = 0
        
        while i < len(tokens):
            token_type, token_value, line_num = tokens[i]
            
            if token_value == '(':
                paren_count += 1
            elif token_value == ')':
                paren_count -= 1
                if paren_count == 0:
                    return i + 2  # 跳过右括号和分号
            
            i += 1
        
        return i
    
    def evaluate_expression(self, tokens):
        """计算表达式的值"""
        if not tokens:
            return None
        
        # 处理简单的情况
        if len(tokens) == 1:
            token_type, token_value, line_num = tokens[0]
            if token_type == 'ID':
                return self.variables.get(token_value, None)
            return token_value
        
        # 处理字符串连接和数学运算
        result = None
        i = 0
        operator = None
        
        while i < len(tokens):
            token_type, token_value, line_num = tokens[i]
            
            if token_type == 'OP':
                operator = token_value
                i += 1
                continue
            
            if result is None:
                result = self.evaluate_expression([tokens[i]])
            elif operator:
                next_val = self.evaluate_expression([tokens[i]])
                
                if operator == '+':
                    # 字符串连接或数字加法
                    if isinstance(result, str) or isinstance(next_val, str):
                        result = str(result) + str(next_val)
                    else:
                        result = self.cast_number(result) + self.cast_number(next_val)
                elif operator == '-':
                    result = self.cast_number(result) - self.cast_number(next_val)
                elif operator == '*':
                    result = self.cast_number(result) * self.cast_number(next_val)
                elif operator == '/':
                    denominator = self.cast_number(next_val)
                    if denominator == 0:
                        raise ZeroDivisionError("Division by zero")
                    result = self.cast_number(result) / denominator
                elif operator == '==':
                    result = result == next_val
                elif operator == '!=':
                    result = result != next_val
                elif operator == '>':
                    result = self.cast_number(result) > self.cast_number(next_val)
                elif operator == '<':
                    result = self.cast_number(result) < self.cast_number(next_val)
                elif operator == '>=':
                    result = self.cast_number(result) >= self.cast_number(next_val)
                elif operator == '<=':
                    result = self.cast_number(result) <= self.cast_number(next_val)
                
                operator = None
            
            i += 1
        
        return result
    
    def import_library(self, lib_name):
        """导入库"""
        if lib_name in self.libraries:
            # 将库函数注册到全局函数表中
            for func_name, func in self.libraries[lib_name].items():
                self.functions[func_name] = func
            print(f"Imported library: {lib_name}")
        else:
            # 尝试从文件加载
            self.load_library_from_file(lib_name)
    
    def load_library_from_file(self, lib_name):
        """从文件加载库"""
        lib_file = f"{lib_name}.bl"
        if os.path.exists(lib_file):
            try:
                with open(lib_file, 'r', encoding='utf-8') as f:
                    lib_code = f.read()
                
                print(f"Loading library from: {lib_file}")
                
                # 执行库代码来注册函数
                lib_interpreter = BraceLangInterpreter()
                lib_interpreter.run(lib_code)
                
                # 将库中的函数添加到当前解释器
                for func_name, func_body in lib_interpreter.functions.items():
                    self.functions[func_name] = func_body
                    
                print(f"Loaded {len(lib_interpreter.functions)} functions from {lib_name}")
                
            except Exception as e:
                print(f"Error loading library {lib_name}: {e}")
        else:
            print(f"Library not found: {lib_name}")
    
    def evaluate(self, ast):
        """执行AST"""
        for node in ast:
            node_type = node[0]
            
            if node_type == 'import':
                lib_name = node[1]
                line_num = node[2]
                self.current_line = line_num
                self.import_library(lib_name)
            
            elif node_type == 'var_decl':
                var_name = node[1]
                expr_tokens = node[2]
                line_num = node[3]
                self.current_line = line_num
                
                try:
                    var_value = self.evaluate_expression(expr_tokens)
                    self.variables[var_name] = var_value
                except Exception as e:
                    print(f"Error at line {line_num}: {e}")
            
            elif node_type == 'func_call':
                func_name = node[1]
                args = node[2]
                line_num = node[3]
                self.current_line = line_num
                
                try:
                    evaluated_args = [self.evaluate_expression(arg) for arg in args]
                    
                    if func_name == 'print':
                        # 处理print函数
                        output = " ".join(str(arg) for arg in evaluated_args)
                        print(output)
                    elif func_name in self.functions:
                        # 调用用户函数或库函数
                        result = self.functions[func_name](evaluated_args)
                        if result is not None:
                            # 如果函数有返回值，可以存储或处理
                            pass
                    else:
                        print(f"Error at line {line_num}: Function '{func_name}' not found")
                
                except Exception as e:
                    print(f"Error at line {line_num}: {e}")
    
    def run(self, code):
        """运行代码"""
        try:
            tokens = self.tokenize(code)
            ast = self.parse(tokens)
            self.evaluate(ast)
        except Exception as e:
            print(f"Error at line {self.current_line}: {e}")

# 主函数
if __name__ == "__main__":
    root = tk.Tk()
    ide = BraceLangIDE(root)
    root.mainloop()